Similar Question
Solution Tips
方案一: 脑筋急转弯
var repeatedSubstringPattern = function (s) {
const str = s + s;
return str.substring(1, str.length - 1).includes(s)
};
方案二: 富途二面 - 临时方案
function checkRepeat(s) {
if (s.length === 0) return false;
const map = {};
for (let i = 0; i < s.length; i++) {
map[s[i]] = (map[s[i]] || 0) + 1;
}
const half = Math.floor(s.length / 2);
const subMap = {};
for (let i = 0; i < half; i++) {
subMap[s[i]] = (subMap[s[i]] || 0) + 1;
const time = canRepeat(map, subMap)
if (time) {
if (s.slice(0, i + 1).repeat(time) === s) {
return true;
}
}
}
return false;
function canRepeat(map, subMap) {
let multiple;
for (const [key, val] of Object.entries(map)) {
const subCount = subMap[key];
if (!multiple) {
multiple = (val / subCount);
}
else if (multiple !== (val / subCount)) {
return false;
}
}
return multiple;
}
}
function checkRepeat2(s) {
if (s.length === 0) return false;
const half = Math.floor(s.length / 2);
for (let i = 0; i < half; i++) {
const sub = s.slice(0, i + 1);
if (s.length % sub.length === 0) {
if (sub.repeat(s.length / sub.length) === s) {
return true;
}
}
}
return false;
}
console.log(checkRepeat2(''));
console.log(checkRepeat2('12312356'));
console.log(checkRepeat2('ababab'));
console.log(checkRepeat2('abcab'));
console.log(checkRepeat2('aaaa'));
console.log(checkRepeat2('abcabcabc'));
console.log(checkRepeat2('abba'));
console.log(checkRepeat2('aabaab'));
console.log(checkRepeat2('abcabc'));